package com.dlkj.threadPool.core.exception;

import com.dlkj.threadPool.core.response.CallResult;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLException;
import java.util.Set;

/**
 * @Author : lei
 * @Company ：DiLang Technology
 * @Date : 2019/1/9 9:45
 * @Description : 异常统一处理
 **/
@RestControllerAdvice
public class CommonExceptionHandler {

    private final static Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ExceptionHandler(ConstraintViolationException.class)
    public CallResult handleConstraintViolation(final ConstraintViolationException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        final Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        final StringBuilder strBuilder = new StringBuilder();
        for (final ConstraintViolation<?> violation : violations) {
            strBuilder.append(violation.getMessage()).append(",");
        }
        return CallResult.callFail(strBuilder.toString());
    }

    @ExceptionHandler({ServiceException.class, ServletException.class})
    public CallResult handleService(final Throwable e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return CallResult.callFail(e.getMessage());
    }

    @ExceptionHandler({SQLException.class, DataAccessException.class})
    public CallResult handleSQL(final Throwable e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return CallResult.callFail("数据库错误");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public CallResult handleNoHandlerFound(final HttpServletRequest request, final Throwable e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return CallResult.callFail(request.getRequestURI() + "接口不存在");
    }

    @ExceptionHandler(Exception.class)
    public CallResult globalException(final HttpServletRequest request, final Throwable e) {
        log.error(e.getMessage());
        e.printStackTrace();
        final String error = String.format("%s => %s", request.getRequestURI(), e.getMessage());
        return CallResult.callFail(error);
    }

    /**
     * 接口参数后端检验
     * 校验失败时会抛出MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CallResult methodArgumentValidExceptionHandler(MethodArgumentNotValidException e) throws Exception {
        String message = null;
        //如果抛出了异常，这个getErrorCount一定会>0
        if (e.getBindingResult().getErrorCount() > 0) {
            //校验会把所有不通过的选项的错误信息记录下来，现在先默认给前端提供第一个错误信息
            String parameterName = e.getBindingResult().getAllErrors().get(0).getObjectName();
            message = "参数：【"+ parameterName +"】异常，异常原因："+  e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        return CallResult.callFail(message);
    }
}
